﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;

namespace NetFrameworkExtensions.BusinessLayer
{
  [Serializable]
  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
  public class IsChildPropertyAttribute : Attribute
  {
    public static PropertyInfo FindProperty<T>()
    {
      return FindProperty(typeof(T));
    }

    public static PropertyInfo FindProperty(Type type)
    {
      if (type == null) throw new ArgumentNullException("type");
      var childProps = type.GetProperties().Where(p => p.CanRead && p.GetIndexParameters().Length == 0 && p.GetCustomAttributes(typeof(IsChildPropertyAttribute), true).Any()).ToArray();
      return childProps.SingleOrDefault();
    }

    public static IList GetPropertyValue(object instance)
    {
      if (instance == null) throw new ArgumentNullException("instance");
      var type = instance.GetType();
      var prop = FindProperty(type);
      var result = prop.GetValue(instance, null);
      return result as IList;
    }
  }
}
